/*
 * Copyright (c) zhg2yqq.com Corp.
 * All Rights Reserved.
 */
package com.zhg2yqq.wheels.security;

import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.zhg2yqq.wheels.security.context.SecurityLoginUser;

import cn.hutool.core.util.IdUtil;

/**
 * @author zhg2yqq, 2022年11月28日
 * @version zhg2yqq v1.0
 */
public class DefaultUserDetailsService implements UserDetailsService {
    private Logger log = LoggerFactory.getLogger(DefaultUserDetailsService.class);

    private ISecurityService securityService;
    private final CustomeSecurityProperties securityProperties;

    public DefaultUserDetailsService(ISecurityService securityService,
                                     CustomeSecurityProperties securityProperties) {
        this.securityService = securityService;
        this.securityProperties = securityProperties;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isBlank(username)) {
            log.info("登录用户：{} 不存在", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }

        // 查出密码
        SecurityLoginUser user = securityService.getLoginUserByName(username);
        if (Objects.isNull(user)) {
            log.info("登录用户：{} 不存在", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }

        return buildAccess(user);
    }

    private SecurityLoginUser buildAccess(SecurityLoginUser user) {
        long customExpireTime = user.getSecurityTtl() == null ? securityProperties.getTokenExpireTime()
                : user.getSecurityTtl();
        user.setSecurityTtl(customExpireTime);
        // 这里的key就是全局处理认证信息的key
        String key = IdUtil.getSnowflakeNextIdStr();
        user.setAccessKey(key);
        return user;
    }
}
